package com.yoomiito.app.ui.order.sureorder.shopcar;

import android.os.Bundle;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.shopcar.ShopCarAdapter;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.base.BaseLazyFragment;
import com.yoomiito.app.model.order.ShopCarGoods;
import com.yoomiito.app.model.order.ShopCarList;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.utils.SpannableUtils;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.SelectView;
import com.yoomiito.app.widget.SpacesItemDecoration;
import com.yoomiito.app.widget.state.ContentType;
import com.yoomiito.app.widget.state.EmptyType;
import com.yoomiito.app.widget.state.StatusManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

public class ShopCarFragment extends BaseLazyFragment<ShopCarPresenter> {
    @BindView(R.id.tv_center)
    TextView mTitleTv;
    @BindView(R.id.tv_right)
    TextView mRightTv;
    @BindView(R.id.goods_total_price)
    TextView mGoodsTotalPrice;
    @BindView(R.id.select_all)
    SelectView mSelectAll;
    @BindView(R.id.frameLayout)
    FrameLayout mFrameLayout;
    @BindView(R.id.del)
    TextView mDeltv;
    @BindView(R.id.make_order)
    TextView mMakeOrderTv;
    @BindView(R.id.shop_car_bottom_view)
    LinearLayout bottomView;
    SmartRefreshLayout mRefreshLayout;
    RecyclerView mRecyclerView;
    private ShopCarAdapter mCarAdapter;
    private int mShopCarStatus = 1;//非编辑状态 1      编辑状态 2
    private int mCurrentPage = 1;
    private int mSelectAllSize = 0;//未下架商品总个数
    private int mTotalSize = 0;//选中商品总数量
    private int mDelGoodsSize = 0;//已下架商品总个数
    private LinkedHashMap<Integer, String> mSelectGoods = new LinkedHashMap<>();//存选择的未下架商品
    private LinkedHashMap<Integer, String> mSelectDelGoods = new LinkedHashMap<>();//存选择的下架商品

    @Override
    public int getLayoutId() {
        return R.layout.fm_shop_car;
    }

    @Override
    public ShopCarPresenter newP() {
        return new ShopCarPresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mTitleTv.setVisibility(View.VISIBLE);
        mRightTv.setVisibility(View.VISIBLE);
        mTitleTv.setText("购物车");
        mRightTv.setText("编辑");
        mStatusManager = new StatusManager.Builder(context)
                .addType(new ContentType(R.layout.fm_rcy))
                .addType(new EmptyType().setEmptyContent("购物车是空的")
                        .setImageResource(R.drawable.shop_car_empty))
                .build();
        mRefreshLayout = mStatusManager.view().findViewById(R.id.fm_refreshLayout);
        mRecyclerView = mStatusManager.view().findViewById(R.id.fm_rcy);
        mFrameLayout.addView(mStatusManager.view());

        initRefreshLayout();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new SpacesItemDecoration(DensityUtil.dp2px(10)));
        mCarAdapter = new ShopCarAdapter(null);
        mCarAdapter.setOnItemClickListener((adapter, view, position) -> {
            ShopCarGoods shopCarGoods = mCarAdapter.getData().get(position);
            if (shopCarGoods.getIs_deleted() == 1) {
                return;
            }
            RouterUtils.toGoodsDetail((BaseActivity) context, String.valueOf(shopCarGoods.getProduct_id()), AllCode.BaoPin);

        });
        mCarAdapter.setItemClickListener((position, isSelected) -> {
            L.i(position + "  " + isSelected);
            ShopCarGoods shopCarGoods = mCarAdapter.getData().get(position);
            if (mShopCarStatus == 1) {//非编辑状态下
                if (isSelected) {
                    mSelectGoods.put(position, shopCarGoods.getProduct_id());
                } else {
                    mSelectGoods.remove(position);
                }
            } else {//编辑状态下
                if (isSelected) {
                    if (shopCarGoods.getIs_deleted() == 0) {//非下架商品
                        mSelectGoods.put(position, shopCarGoods.getProduct_id());
                    } else {//下架商品
                        mSelectDelGoods.put(position, shopCarGoods.getProduct_id());
                    }
                } else {
                    if (shopCarGoods.getIs_deleted() == 0) {
                        mSelectGoods.remove(position);
                    } else {
                        mSelectDelGoods.remove(position);
                    }
                }
            }
            L.i("数: " + mSelectAllSize + "  " + mSelectGoods.size());

            if (mShopCarStatus == 1) {//非编辑状态下
                mSelectAll.setSelect(mSelectAllSize == mSelectGoods.size());
            } else {//编辑状态
                mSelectAll.setSelect((mSelectAllSize + mDelGoodsSize) == (mSelectGoods.size() + mSelectDelGoods.size()));
            }
            showTotalPriceAndSize();
        });
        mCarAdapter.setOnNumChangeListener((position, num) -> {
            showLoading();
            ShopCarGoods shopCarGoods = mCarAdapter.getData().get(position);

            getP().addShopCar(shopCarGoods.getProduct_id(), num, position);
        });
        mRecyclerView.setAdapter(mCarAdapter);

        mSelectAll.setClickListener(v -> {//全选  取消全选
            mSelectGoods.clear();
            mSelectDelGoods.clear();
            List<ShopCarGoods> shopCarGoods = mCarAdapter.getData();
            for (int i = 0; i < shopCarGoods.size(); i++) {
                ShopCarGoods goods = shopCarGoods.get(i);
                goods.setSelect(mSelectAll.isSelected());
                if (mSelectAll.isSelected()) {
                    if (goods.getIs_deleted() == 0) {
                        mSelectGoods.put(i, goods.getProduct_id());
                    } else {
                        mSelectDelGoods.put(i, goods.getProduct_id());
                    }
                }
            }
            mCarAdapter.notifyDataSetChanged();
            showTotalPriceAndSize();
        });

        getP().getList();

    }

    @Override
    protected void onStartLazy() {
        super.onStartLazy();

    }

    private void initRefreshLayout() {
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(refreshLayout -> {
            getP().getList();
        });
        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {//不要加载更多
//            getP().getList(mCurrentPage + 1);
        });
    }

    public void setData(ShopCarList shopCarList) {
        if (shopCarList.getData() == null || shopCarList.getData().size() == 0) {
            bottomView.setVisibility(View.GONE);
            mStatusManager.showEmpty();
            mRightTv.setVisibility(View.GONE);
        } else {
            bottomView.setVisibility(View.VISIBLE);
            mRightTv.setVisibility(View.VISIBLE);
            mCarAdapter.setNewData(shopCarList.getData());
            getSelectSize(shopCarList.getData());
        }
        mRefreshLayout.finishRefresh(true);
        mSelectGoods.clear();
        showTotalPriceAndSize();
//        if (shopCarList.getCurrent_page()==1){
//            if (shopCarList.getData()==null||shopCarList.getData().size()==0){
//                mStatusManager.showEmpty();
//            }else {
//                mStatusManager.showContent();
////                mCarAdapter.setNewData(shopCarList.getData());
//                mRefreshLayout.finishRefresh(true);
//            }
//        }else {
////            mCarAdapter.addData(shopCarList.getData());
//            mRefreshLayout.finishLoadMore(true);
//        }
//        if (shopCarList.getCurrent_page()==shopCarList.getLast_page()){//最后一页
//            mRefreshLayout.finishLoadMoreWithNoMoreData();
//        }
//        mCurrentPage = shopCarList.getCurrent_page();
    }

    //获取有效可选择的数
    private void getSelectSize(List<ShopCarGoods> shopCarGoods) {
        mSelectAllSize = 0;
        mDelGoodsSize = 0;
        for (ShopCarGoods goods : shopCarGoods) {
            if (goods.getIs_deleted() == 0) {
                mSelectAllSize++;
            } else {
                mDelGoodsSize++;
            }
        }
    }

    /**
     * 计算总价
     *
     * @return
     */
    private String calculatePriceSum() {
//        Iterator<Map.Entry<Integer,Long>> iterator = mSelectGoods.entrySet().iterator();
//        while (iterator.hasNext()){
//            Map.Entry<Integer,Long> next = iterator.next();
//        }
        String price = "0.00";
        mTotalSize = 0;
        List<ShopCarGoods> shopCarGoods = mCarAdapter.getData();
        Set<Integer> set = mSelectGoods.keySet();
        for (Integer i : set) {
            ShopCarGoods goods = shopCarGoods.get(i);
            price = AllUtils.priceSum_2(price, AllUtils.priceMul(goods.getSale_price(), goods.getNum()));
            mTotalSize += goods.getNum();
        }
        return price;
    }

    public void showTotalPriceAndSize() {
        if (mSelectGoods.size() == 0) {
            mSelectAll.setSelect(false);
        }
        String totalPrice = calculatePriceSum();
        String price = "共" + mTotalSize + "件 合计¥" + totalPrice;
        int p = price.indexOf("¥");
        mGoodsTotalPrice.setText(SpannableUtils.getSizeAndPriceText(price, R.color.color_ff5100, p, price.length(), p, p + 1));
    }

    @OnClick({R.id.iv_back_left, R.id.tv_right, R.id.del, R.id.make_order})
    public void onClick(View view) {
        Set<Integer> set = mSelectGoods.keySet();
        List<ShopCarGoods> goodsDetails = mCarAdapter.getData();

        switch (view.getId()) {
            case R.id.iv_back_left:
                context.finish();
                break;
            case R.id.tv_right:
                if ("编辑".equals(mRightTv.getText())) {
                    mRightTv.setText("完成");
                    mShopCarStatus = 2;
                    mDeltv.setVisibility(View.VISIBLE);
                    mMakeOrderTv.setVisibility(View.GONE);
                    mGoodsTotalPrice.setVisibility(View.GONE);
                } else {
                    mRightTv.setText("编辑");
                    mShopCarStatus = 1;
                    mGoodsTotalPrice.setVisibility(View.VISIBLE);
                    mMakeOrderTv.setVisibility(View.VISIBLE);
                    mDeltv.setVisibility(View.GONE);
                }
                mCarAdapter.setShopCarStatus(mShopCarStatus);
                break;
            case R.id.del:
                if (mSelectGoods.size() == 0 && mSelectDelGoods.size() == 0) {
                    YMToast.showText("请选择商品");
                    return;
                }
                Set<Integer> delGoodsSet = mSelectDelGoods.keySet();
                String params = "";

                for (Integer i : set) {
                    params += goodsDetails.get(i).getProduct_id() + ",";
                }
                for (Integer i : delGoodsSet) {
                    params += goodsDetails.get(i).getProduct_id() + ",";
                }
                if (params.endsWith(",")) {
                    params = params.substring(0, params.length() - 1);
                }
                L.i("删除参数: " + params);
                getP().delGoodsFromShopCar(params);
                break;
            case R.id.make_order:
                if (mSelectGoods.size() == 0) {
                    YMToast.showText("请选择商品");
                    return;
                }
                ArrayList<ShopCarGoods> details = new ArrayList<>();
//                Set<Integer> set_1 = mSelectGoods.keySet();
//                List<ShopCarGoods> goodsDetails = mCarAdapter.getData();
                for (Integer i : set) {
                    L.i("选中商品：" + i);
                    details.add(goodsDetails.get(i));
                }
                ShopCarBuyGoodsActivity.start(context, details);
                break;
        }
    }

    /**
     * 刷新数据
     */
    private void notifyData() {
        showLoading();
        mSelectGoods.clear();
        getP().getList();
    }

    public void delSuccess() {
        mSelectDelGoods.clear();
        EventMessage eventMessage = new EventMessage();
        eventMessage.setEventType(AllCode.NotifyShopCarData);
        EventBus.getDefault().postSticky(eventMessage);
    }

    public void numChangeSuccess(int position, int num) {//数量修改成功  则将修改后的数量设置到相应的商品中
        List<ShopCarGoods> shopCarGoods = mCarAdapter.getData();
        ShopCarGoods shopCarGoods1 = shopCarGoods.get(position);
        shopCarGoods1.setNum(num);
        showTotalPriceAndSize();
    }

    public void numChangeFail() {//数量修改失败 则将数据修改为原数据  因为是先改数据并显示 后提交服务器  所以失败后 要重新刷新数据
        mCarAdapter.notifyDataSetChanged();
//        showTotalPriceAndSize();
    }

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        L.i("购物车--收到信息111");
        //订单生成后 通知购物车刷新数据
        //删除订单后  通知购物车刷新数据
        if (AllCode.NotifyShopCarData.equals(eventMessage.getEventType())) {
            L.i("购物车--开始刷新");
            notifyData();
        }
    }
}
